package com.vayne.demo;

import com.vayne.bean.Course;
import com.vayne.dao.CourseDao;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 依赖注入
 *
 * @author xuerui.zhang
 * @since 2020/1/6 下午6:31
 */
public class DependencyInjectionDemo {

    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("dependency_injection_config.xml");
        // findSingleByType(beanFactory);

        // 1、自定义的 Bean 对象：CourseDao
        CourseDao courseDao = beanFactory.getBean("courseDao", CourseDao.class);

        // 这个 BeanFactory 怎么来的
        // TODO BeanFactory 并不是一个普通的 Bean，那它到底是什么
        // 2）容器内建依赖
        System.out.println(courseDao.getBeanFactory());

        // 这是依赖注入 courseDao.getBeanFactory())
        // 这两个 beanFactory 为什么一样？
        // 1）ApplicationContext 就是 BeanFactory，只不过是不同的对象
        // 2) https://docs.spring.io/spring/docs/5.2.3.RELEASE/spring-framework-reference/core.html#beans-introduction
        // 3）The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object（对象）.
        // 4）ApplicationContext is a sub-interface of BeanFactory. It adds:
        //      a.Easier integration with Spring’s AOP features
        //      b.Message resource handling (for use in internationalization)
        //      c.Event publication
        //      d.Application-layer specific contexts such as the WebApplicationContext for use in web applications.
        System.out.println(beanFactory == courseDao.getBeanFactory());

        // 这里是依赖查找(FIXME  这里执行是报错的，因为是内建 bean )
        // System.out.println(beanFactory.getBean(BeanFactory.class));

        ObjectFactory<Course> objectFactory = courseDao.getObjectFactory();
        System.out.println(objectFactory.getObject());

        // 3、容器内建 Bean
        Environment bean = beanFactory.getBean(Environment.class);
        System.out.println(bean);
    }

    /**
     * 硬编码形式：getter & setter
     */
    private static void findSingleByType(BeanFactory beanFactory) {
        CourseDao courseDao = beanFactory.getBean("courseDao", CourseDao.class);
        System.out.println(courseDao.getCourses());
    }
}
